package com.zhangye.test.service;

import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

import org.apache.commons.collections.MapUtils;
import org.dom4j.DocumentException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.zhangye.test.mapper.AccountMapper;
import com.zhangye.test.mapper.AccountPayMapper;
import com.zhangye.test.mapper.WechatOrderInfoMapper;
import com.zhangye.test.model.AccountPay;
import com.zhangye.test.model.Business;
import com.zhangye.test.model.WechatOrderInfo;
import com.zhangye.test.util.HttpTookit;
import com.zhangye.test.util.Sign;
import com.zhangye.test.util.StringUtils;
import com.zhangye.test.util.XMLPojoMapConverter;


@Service
public class WeChatQueryService {

	Logger logger = LoggerFactory.getLogger(WeChatQueryService.class);
	
	@Autowired
	private WechatOrderInfoMapper wechatOrderInfoMapper;

	@Autowired
	private AccountMapper accountMapper;

	@Autowired
	private AccountPayMapper accountPayMapper;

	@Autowired
	private PayListService payListService;

	@Autowired
	private BusinessService businessService;
	
	
	/**
	 * 提现
	 * 作者： 张叶
	 * 创建时间：2018年11月6日  下午2:09:09
	 */
	public void transfers(){
		//https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers  接口地址
		
	}
	

	
	public Map<String, Object> queryNew(Map<String, String> param) throws ParseException, DocumentException {
		AccountPay acp;
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, Object> results = new HashMap<String, Object>();
		Map<String, Object> transaction_id = null;
		Map<String, Object> return_code = null;
		Map<String, Object> result_code = null;
		Map<String, Object> trade_state = null;
		Map<String, Object> time_end = null;
		Map<String, Object> trade_state_desc = null;
		String out_trade_no = param.get("outTradeNo");
		String order = "";
		if (param.get("order")!=null&&!param.get("order").equals("")) {
			order = param.get("order");
		}
		String result = "";
		String tradestate = "";
		String res = "";
		results.put("status", "1");
		
		//查询异步支付结果
		WechatOrderInfo who = new WechatOrderInfo();
		String where = " and outTradeNo = '" + param.get("outTradeNo") + "'";
		List<WechatOrderInfo> weChatOrder = wechatOrderInfoMapper.selectByWhere(where);
		if (weChatOrder.size() > 0) {
			String body = weChatOrder.get(0).getBody();
			results.put("outTradeNo", param.get("outTradeNo"));
			if (weChatOrder.get(0).getResultcodeAsync() != null
					&& !weChatOrder.get(0).getResultcodeAsync().equals("")
					&& weChatOrder.get(0).getResultcodeAsync() != null
					&& weChatOrder.get(0).getResultcodeAsync().equals("")) {
				String ResultCode_async = weChatOrder.get(0)
						.getResultcodeAsync();
				String ReturnCode_async = weChatOrder.get(0)
						.getResultcodeAsync();
				if (ResultCode_async.equals("SUCCESS")
						&& ReturnCode_async.equals("SUCCESS")) {
					results.put("status", "0");
				} else {
					results.put("status", "3");
				}
			} else {
				double total_amount = weChatOrder.get(0).getTotalamount();
				SortedMap<Object,Object> parameters = new TreeMap<Object,Object>();  
				parameters.put("appid", "wx10331e9b86cb6027"); //微信开放平台审核通过的应用APPID
				parameters.put("mch_id", "1406370302"); 	   //微信支付分配的商户号
				parameters.put("nonce_str", StringUtils.generatorNumber(15)); //随机字符串，不长于32位
				parameters.put("out_trade_no", out_trade_no);  //系统内部的订单号,
				
				String mySign = Sign.createSign("UTF-8",parameters);  
				parameters.put("sign", mySign);
				
				//转换xml
				byte[] aa = XMLPojoMapConverter.callMapToXML(parameters);
				String data = new String(aa);
				
				//调用微信查询订单接口
				String url = "https://api.mch.weixin.qq.com/pay/orderquery";
				result = HttpTookit.httpsRequest(url, "POST", data);
				
				//xml转换map
				map = XMLPojoMapConverter.xml2map(result); 
				if (MapUtils.isNotEmpty(map)) {
					return_code = (Map<String, Object>) map.get("return_code");
					result_code = (Map<String, Object>) map.get("result_code");
					trade_state = (Map<String, Object>) map.get("trade_state");
					if (return_code.get("return_code").equals("SUCCESS")
							&& result_code.get("result_code").equals("SUCCESS")) {
						transaction_id = (Map<String, Object>) map.get("transaction_id");
						time_end = (Map<String, Object>) map.get("time_end");
						tradestate = (String) trade_state.get("trade_state");
						trade_state_desc = (Map<String, Object>) map.get("trade_state_desc");
					}

//					if (trade_state_desc == null
//							|| trade_state_desc.get("trade_state_desc") == null
//							|| trade_state_desc.get("trade_state_desc").equals("")) {
					if (trade_state_desc != null) {
						//更新订单信息
						who = new WechatOrderInfo();
						who.setTradeState(tradestate);
						who.setOuttradeno(out_trade_no);
						who.setUpdatetime(StringUtils.format(StringUtils.getCurrentDateTime(), "yyyy-MM-dd HH:mm:ss"));
						who.setTransactionId(transaction_id.get("transaction_id").toString());
						who.setTimeEnd(time_end.get("time_end").toString());
						int i = wechatOrderInfoMapper.updateByPrimaryKey(who);
						if (i == 0) {
							logger.info("交易成功，更新weChatOrderInfo表失败，订单号：" + out_trade_no);
						}
						
						if (order!=null&&!order.equals("")) {
							//支付成功通知PHP
							Map<String, String> datas = new HashMap<String, String>();
							String url1 = "http://xingtai114.zhyell.com/numberorder/payed";
							datas.put("order", order);
							datas.put("payorder", out_trade_no);
							res = HttpTookit.doGet(url1, datas);
						}
						acp = new AccountPay();
						acp.setUserid(weChatOrder.get(0).getUserid());
						acp.setInserttime(StringUtils.format(StringUtils.getCurrentDateTime(), "yyyy-MM-dd HH:mm:ss"));
						acp.setTotalamount(Double.valueOf(total_amount));
						acp.setBalance(total_amount);
						acp.setVariation("+"+total_amount);
						acp.setPayway("微信支付");
						acp.setOuttradeno(out_trade_no);
						acp.setPhporder(order);
						acp.setPhpresult(res);
						acp.setDeletelogo(0);
						int p = accountPayMapper.insert(acp);
						if (p == 1) {
							//支付成功更新业务表
							int b = 0;
							Long mId = (long)weChatOrder.get(0).getUserid();
							Business bus = businessService.selectBymId(mId);
							if (bus == null || bus.equals("")) {
								if (body.equals("挂机短信")) {
									bus.setMarketingStarttime(new Date());
									bus.setMarketingEndtime(StringUtils.format(StringUtils.getDateAdd(weChatOrder.get(0).getMonthcount(), StringUtils.getCurrentDateTime(), "month", "yyyy-MM-dd HH:mm:ss"), "yyyy-MM-dd HH:mm:ss"));
									bus.setWebsiteStarttime(new Date());
									bus.setWebsiteEndtime(new Date());
									bus.setCardStarttime(new Date());
									bus.setCardEndtime(new Date());
								} else {
									bus.setMarketingStarttime(new Date());
									bus.setMarketingEndtime(StringUtils.format(StringUtils.getDateAdd(weChatOrder.get(0).getMonthcount(), StringUtils.getCurrentDateTime(), "month", "yyyy-MM-dd HH:mm:ss"), "yyyy-MM-dd HH:mm:ss"));
									bus.setWebsiteStarttime(new Date());
									bus.setWebsiteEndtime(new Date());
									bus.setCardStarttime(new Date());
									bus.setCardEndtime(StringUtils.format(StringUtils.getDateAdd(weChatOrder.get(0).getMonthcount(), StringUtils.getCurrentDateTime(), "month", "yyyy-MM-dd HH:mm:ss"), "yyyy-MM-dd HH:mm:ss"));
								}
								bus.setDeletelogo(0);
								b = businessService.insert(bus);
							} else {
								Date now = new Date();
								if (body.equals("挂机短信")) {
									Date marketingEndtime = bus.getMarketingEndtime();
									if(marketingEndtime.before(now)){
										bus.setMarketingEndtime(StringUtils.format(StringUtils.getDateAdd(weChatOrder.get(0).getMonthcount(), StringUtils.formatDate(now, "yyyy-MM-dd HH:mm:ss"), "month", "yyyy-MM-dd HH:mm:ss"), "yyyy-MM-dd HH:mm:ss"));	
									}else{
										bus.setMarketingEndtime(StringUtils.format(StringUtils.getDateAdd(weChatOrder.get(0).getMonthcount(), StringUtils.formatDate(marketingEndtime, "yyyy-MM-dd HH:mm:ss"), "month", "yyyy-MM-dd HH:mm:ss"), "yyyy-MM-dd HH:mm:ss"));
									}
								} else {
									Date cardEndTime = bus.getCardEndtime();
									if(cardEndTime.before(now)){
										bus.setCardEndtime(StringUtils.format(StringUtils.getDateAdd(weChatOrder.get(0).getMonthcount(), StringUtils.formatDate(now, "yyyy-MM-dd HH:mm:ss"), "month", "yyyy-MM-dd HH:mm:ss"), "yyyy-MM-dd HH:mm:ss"));	
									}else{
										bus.setCardEndtime(StringUtils.format(StringUtils.getDateAdd(weChatOrder.get(0).getMonthcount(), StringUtils.formatDate(cardEndTime, "yyyy-MM-dd HH:mm:ss"), "month", "yyyy-MM-dd HH:mm:ss"), "yyyy-MM-dd HH:mm:ss"));	
									}
									Date marketingEndtime = bus.getMarketingEndtime();
									if(marketingEndtime.before(now)){
										bus.setMarketingEndtime(StringUtils.format(StringUtils.getDateAdd(weChatOrder.get(0).getMonthcount(), StringUtils.formatDate(now, "yyyy-MM-dd HH:mm:ss"), "month", "yyyy-MM-dd HH:mm:ss"), "yyyy-MM-dd HH:mm:ss"));	
									}else{
										bus.setMarketingEndtime(StringUtils.format(StringUtils.getDateAdd(weChatOrder.get(0).getMonthcount(), StringUtils.formatDate(marketingEndtime, "yyyy-MM-dd HH:mm:ss"), "month", "yyyy-MM-dd HH:mm:ss"), "yyyy-MM-dd HH:mm:ss"));
									}
								}
								b = businessService.update(bus);
							}
							if (b == 1) {
								results.put("status", "0");
							} else {
								logger.info("交易成功，更新业务表business失败，订单号："
										+ out_trade_no);
							}
						} else {
							logger.info("交易成功，插入account_pay表失败，订单号："
									+ out_trade_no);
						}
					} else {
						//更新订单信息
						who = new WechatOrderInfo();
						who.setTradeState(trade_state_desc.toString());
						who.setOuttradeno(out_trade_no);
						who.setUpdatetime(StringUtils.format(StringUtils.getCurrentDateTime(), "yyyy-MM-dd HH:mm:ss"));
						who.setTransactionId("");
						who.setTimeEnd("");
						wechatOrderInfoMapper.updateByPrimaryKey(who);
						results.put("status", "4");
						results.put("desc", trade_state_desc.get("trade_state_desc"));
					}
				}
			}
		} else {
			results.put("status", "2");
		}
		
		return results;
	}

}
